const express=require('express');
const http=require('http');
const socketIO=require('socket.io');
const app=express();
const server=http.createServer(app);

const io = socketIO(server,{
    cors: {
        origin: 'http://localhost:8080'
    }
});

var users=[];   //保存进入房间的用户
// let count=0;  //保存当前在线人数
io.on('connection',(socket) => {
    // console.log(socket.id);
    console.log("保存的用户有",users)
    // 当前在线人数++
    // count++;
    io.emit('count_updated', users.length);

    // 监听客户端的断开
    socket.on('disconnect', (reason)=>{
        // 断开时，当前在线人数--
        // count--;
        
    })
    //接收进入的用户名称
    socket.on('toLive',(data)=>{
        // console.log(data)
        var user=users.find(item=>item.username===data.username)
        if(!user){
            users.push(data.username)
        }
        io.emit("userlist",data.username)
        // 把用户名保存起来
        socket.username=data.username
    });
    //退出tolive时
    socket.on("dislive",(data)=>{
        users.remove(data)
        io.emit('count_updated', users.length)
    })
    //接收客户端发来的消息
    socket.on("sendMsg",(data)=>{
        // console.log(data)
        //向客户端返回发来的消息
        io.emit("sendtext",data)
    })

});
 
 
// app.get('/studio',(request, response) => {
//     io.emit('message','服务端向客户端推送消息...');
//     response.writeHead(200, {"Content-type": "text/plain"});
//     response.end();
// });

 
server.listen(9999,() => {
    console.log("server is up and running on port 9999");
});
